package com.weipt.juc.syncollector;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;

/**
 * @author peter.wei 2020/09/15 19:38
 * @version 1.0
 * @company 终生学习
 * @description <br>peter.wei 2020/09/15 19:38
 **/
public class TestCopyOnWriteList {

    private static List<String> list = new ArrayList<>();

    //同步代码块
    private static List<String> synList = Collections.synchronizedList(new ArrayList<>());

    /**public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;
        return true;
    }*/
    private static Vector vector = new Vector();  //arrayList的安全版本,方法上加了synchronized关键字，效率最低


    //读写分离，写复制
    /**public boolean add(E e) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            Object[] elements = getArray();
            int len = elements.length;
            Object[] newElements = Arrays.copyOf(elements, len + 1);
            newElements[len] = e;
            setArray(newElements);
            return true;
        } finally {
            lock.unlock();
        }
    }*/
    private static List<String> cowList = new CopyOnWriteArrayList<>();


    //提示java.util.ConcurrentModificationException
    //提示数组越界
    //数据长度不符合预期，数据内容不符合预期
    public static void main(String[] args) throws InterruptedException {
        /*for (int i = 0; i < 10; i++) {
            new Thread(()->{
                TestCopyOnWriteList.putList();
            }).start();
        }*/

        /*for (int i = 0; i < 10; i++) {
            new Thread(()->{
                TestCopyOnWriteList.putSynList();
            }).start();
        }*/

        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                TestCopyOnWriteList.putVector();
            }).start();
        }

        /*for (int i = 0; i < 10; i++) {
            new Thread(()->{
                TestCopyOnWriteList.putCowList();
            }).start();
        }*/
        TimeUnit.SECONDS.sleep(1);  //等待5s，让子线程执行完
        System.out.println(list.size());
        System.out.println(synList.size());
        System.out.println(vector.size());
        System.out.println(cowList.size());

    }

    public static void putList(){
        for (int i = 0; i < 50; i++) {
            list.add(String.valueOf(i));
        }
    }

    public static void putSynList(){
        for (int i = 0; i < 50; i++) {
            synList.add(String.valueOf(i));
        }
    }

    public static void putVector(){
        for (int i = 0; i < 50; i++) {
            vector.add(String.valueOf(i));
        }
    }

    public static void putCowList(){
        for (int i = 0; i < 50; i++) {
            cowList.add(String.valueOf(i));
        }
    }
}